import Taro from "@tarojs/taro";

// 获取当前语言设置
export const getCurrentLocale = async () => {
  try {
    const res = await Taro.getStorage({ key: "appLanguage" });
    return res.data === "enUS" ? "enUS" : "zhCN";
  } catch (error) {
    return "zhCN"; // 默认中文
  }
};

// 设置语言
export const setLocale = async (localeCode) => {
  await Taro.setStorage({ key: "appLanguage", data: localeCode });
};

// 语言切换 Hook
export const useLocale = () => {
  const [currentLocale, setCurrentLocale] = useState("zhCN");

  useEffect(() => {
    getCurrentLocale().then((locale) => {
      setCurrentLocale(locale);
    });
  }, []);

  const switchLocale = () => {
    const newLocale = currentLocale === "zhCN" ? "enUS" : "zhCN";
    setCurrentLocale(newLocale);
    setLocale(newLocale);
  };

  return {
    locale: currentLocale,
    switchLocale,
    isEnglish: currentLocale === "enUS",
  };
};
